<?php
namespace App\Http\Controllers;

use App\ErrorCode;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;
use App\Help\Help;
class MemberController extends Controller
{
    public function __construct(Request $request)
    {
        $this->setParam($request);
    }


    /** 会员注册
     * @return array
     */
    public function register(){
        $phone = $this->getParam('phone');
        $password = $this->getParam('password');
        $name = $this->getParam('name');
        $type = $this->getParam('type');//1前台注册 2后台添加

        if(empty($phone) || empty($password) || empty($name)){
            return $this->output(false, ErrorCode::PARAM_ERROR);
        }

        $bool = DB::table('member')
            ->insert([
                'phone' => $phone,
                'password' => md5($password),
                'name' => $name,
                'type' =>$type,
                'createTime' => time()
            ]);
        if(!$bool){
            return $this->output(false,ErrorCode::OPERATION_ERROR);
        }
        return $this->output('success');
    }

    /** 获取api_token (登录之前获取)
     * @return array
     */
    public function getToken( ){

        $userName = $this->getParam('phone');
        $passWord = $this->getParam('passWord');

        if (empty($userName) || empty($passWord)){
            return $this->output(false, ErrorCode::PARAM_NOT_EMPTY);
        }
        $member = Member::where('phone', '=', $userName)
            ->where('password', '=', md5($passWord))
            ->first();
        $data = [];
        if (!empty($member)) {
            $token=str_random(60);
            $member->api_token=$token;
            $member->save();
            $data['api_token'] = $member->api_token;
            return $this->output($data);
        } else {
            return $this->output(false, ErrorCode::USERNAME_NOT_EXISTS);
        }
    }

    /** 会员登陆
     * @return array
     */
    public function login(){
        /**©
         * 校验header 的 api_token
         */
        $userInfo = Auth::user();
        if (empty($userInfo)){
            return $this->output(false, ErrorCode::USERNAME_NOT_EXISTS);
        }
        $result['memberInfo'] = [
            'id' => $userInfo['id'],
            'name' => $userInfo['name'],
            'phone' => $userInfo['phone'],
            'memberPic' => $userInfo['memberPic'],
            'email' => $userInfo['email'],
            'api_token' => $userInfo['api_token']
        ];
        return $this->output($result);
    }

    /** 修改用户信息
     * @return array
     */
    public function updateInfo(){
        $memberId = $this->getParam('memberId');
        $name = $this->getParam('name');
        $phone = $this->getParam('phone');
        $email = $this->getParam('email');
        if(empty($memberId) || empty($name) || empty($phone) || empty($email)){
            return $this->output(false,ErrorCode::PARAM_ERROR);
        }
        $num = DB::table('member')
            ->where('id',$memberId)
            ->update([
                'name' => $name,
                'phone' => $phone,
                'email' => $email,
                'updateTime' => time()
            ]);
        if(!$num){
            return $this->output(false,ErrorCode::OPERATION_ERROR);
        }
        $info = DB::table('member')
            ->where('id',$memberId)
            ->select('id','name','phone','memberPic','email','api_token')
            ->first();
        $info = json_decode(json_encode($info),1);
        return $this->output($info);
    }

    /**修改密码
     * @return array
     */
    public function updatePwd(){
        $phone = $this->getParam('phone');
        $oldPwd = $this->getParam('oldPwd');
        $newPwd = $this->getParam('newPwd');
        if(empty($phone) || empty($oldPwd) || empty($newPwd)){
            return $this->output(false,ErrorCode:: PARAM_ERROR);
        }
        $count = DB::table('member')
            ->where('phone',$phone)
            ->where('password',md5($oldPwd))
            ->count();
        if($count <= 0){
            return $this->output(false,ErrorCode::PWD_ERROR);
        }
        $num = DB::table('member')
            ->where('phone',$phone)
            ->where('password',md5($oldPwd))
            ->update([
                'password' => md5($newPwd),
                'updateTime' =>time()
            ]);
        if(!$num){
            return $this->output(false,ErrorCode::OPERATION_ERROR);
        }
        return $this->output('success');
    }

    /** 检查手机号是否存在
     * @return array
     */
    public function checkPhone(){
        $phone = $this->getParam('phone');
        $count = DB::table('member')
            ->where('phone',$phone)
            ->count();
        if($count>0){
            return $this->output(false,ErrorCode::PHONE_EXIST);
        }
        return $this->output('success');
    }

    /** 获取会员信息
     * @return array
     */
    public function getMemberInfo(){
        $phone = $this->getParam('phone');
        if(empty($phone)){
            return $this->output(false,ErrorCode::PARAM_ERROR);
        }
        $list = DB::table('member')
            ->where('phone',$phone)
            ->select('id','name','phone','memberPic','email','api_token')
            ->first();
        $list = json_decode(json_encode($list),1);
        return $this->output($list);
    }


    public function getMemberList(){
        $keyword = $this->getParam('keyWord');
        $start = $this->getParam('start');
        $num = $this->getParam('num');

        if(empty($start) && empty($num)){
            return $this->output(false,ErrorCode::OPERATION_ERROR);
        }
        $lists = DB::table('member');
        $lists ->select('id','memberPic as PicUrl','name','phone','email','createTime');
        if (!empty($keyword)){
            $key = '%' . $keyword . '%';
            $lists->where(function (Builder $query) use($key){
                $query->where('name','like',$key)
                    ->orWhere('phone','like', $key);
                return $query;
            });
        }
        $lists->orderby('createTime', 'desc');
        if ((int)$num !== -1){
            $list =  $lists->skip($start)->take($num)->get();
        }else{
            $list = $lists->get();
        }

        $res['count'] = count($list);
        $res['items'] = $list;

        return $this->output($res);
    }

    public function del(){
        $id = $this->getParam('id');
        if(empty($id)){
            return $this->output(false,ErrorCode::PARAM_ERROR);
        }
        //foreach ($memberIds as $memberId){
            $num = DB::table('member')
                ->where('id',$id)
                ->delete();
            if(!$num){
                return $this->output(false,ErrorCode::OPERATION_ERROR);
            }
        //}
       return $this->output('success');
    }

    public function  insertMember(){
        $phone = $this->getParam('phone');
        $password = $this->getParam('password');
        $name = $this->getParam('name');
        $email = $this->getParam('email');
        $memberPic = $this->getParam('memberPic');
        $type = $this->getParam('type');//1前台注册 2后台添加

        if(empty($phone) || empty($password) || empty($name)){
            return $this->output(false, ErrorCode::PARAM_ERROR);
        }

        $bool = DB::table('member')
            ->insert([
                'phone' => $phone,
                'password' => md5($password),
                'name' => $name,
                'email'=>$email,
                'memberPic' =>$memberPic,
                'type' =>$type,
                'createTime' => time()
            ]);
        if(!$bool){
            return $this->output(false,ErrorCode::OPERATION_ERROR);
        }
        return $this->output('success');
    }

    /** 修改会员头像
     * @return array
     */
    public function updatePic(){
        $memberId = $this->getParam('id');
        $pic = $this->getParam('memberPic');
        if(empty($memberId) || empty($pic)){
            return $this->output(false,ErrorCode::PARAM_ERROR);
        }
        $num = DB::table('member')
            ->where('id',$memberId)
            ->update([
                'memberPic' => $pic,
                'updateTime' => time()
            ]);
        if(!$num){
            return $this->output(false,ErrorCode::OPERATION_ERROR);
        }
        $info = DB::table('member')
            ->where('id',$memberId)
            ->select('id','name','phone','memberPic','email','api_token')
            ->first();
        $info = json_decode(json_encode($info),1);
        return $this->output($info);
    }
    /**发送短信验证码
     * @return mixed
     */
    public function sendSmsCode(){
        $phone = $this->getParam('phone');
        if (empty($phone)){
            return $this->output(false, ErrorCode::PARAM_NOT_EMPTY);
        }

     

//
//        $verKey = 'wBase:sms:code:' . $phone;
//        $redis = app('redis');
//        $sendCodeTime = $redis->ttl($verKey);
//
//        if ($sendCodeTime > 0){
//            return $this->output(false, ErrorCode::SMS_CODE_MORE);
//        }

        $smsCode = Help::getCheckCode();
//        $redis->set($verKey, $smsCode);
//        $redis->expire($verKey, 90);
        $content = '【产品手记】您的短信验证码是'.$smsCode.'。产品手记：一个真正以知识迭代为核心，互联网思维的产品经理学习、互助、分享平台。';
        $data = Help::sendSmsCode($phone, $content);
        if ($data[1] == 0){
            $cont=DB::table('smscode')
                ->where('phone','=',$phone)
                ->get();
            if(!empty($cont)){
                DB::table('smscode')
                    ->where('phone','=',$phone)
                    ->delete();
            }
            $num=DB::table('smscode')
                ->insert([
                    'phone'=>$phone,
                    'smscode'=>$smsCode,
                    'createTime'=>time()
                ]);
                if($num){
                    return $this->output('短信验证码60秒有效期');

                }else{
                    return $this->output(false, ErrorCode::SMS_CODE_FAILD);
                }
        }else{
            return $this->output(false, ErrorCode::SMS_CODE_FAILD);
        }
    }
    public function getsmscode(){
        $phone=$this->getParam('phone');
        $detil=DB::table('smscode')
            ->where('phone','=',$phone)
            ->get();
        return $this->output($detil);
    }
}